// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// s [author] rhyme_lph
// b [email]  rhymelph@gmail.com
// i [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:dio/src/response.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/purchase_order_entity.dart';
import 'package:finance_app/src/http_service/http_purchase_order_service.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/refresh_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:flutter/material.dart';

class PurchaseOrderNumberProvider
    extends BaseProvider<List<PurchaseOrderEntity>>
    with
        SearchDataListMixin<List<PurchaseOrderEntity>>,
        FormatGroupMapLocalMixin<PurchaseOrderEntity>,
        RefreshMixin<List<PurchaseOrderEntity>, List<PurchaseOrderEntity>>,
        CheckPlanMixin {
  PurchaseOrderEntity currentSelect;

  int contactId;

  String keyword;

  @override
  Future get dataFuture => HttpPurchaseOrderService.purchaseOrdersList(page,
      status: "open", issue_to: contactId, keyword: keyword);

  void onNavAddPurchaseOrder() async {
    if (isPlanExpired()) return;
    final result = await Routes.navigateTo(
        RouterGenProviders.newPurchaseOrderPage,
        params: {
          'isSelectMode': true,
        });
    if (result != null) {
      data.add(currentSelect);
      onSelect(result);
    }
  }

  void onSelect(PurchaseOrderEntity value) {
    if (currentSelect == value) return;
    currentSelect = value;
    update();
    obtainContext?.call((context) {
      Navigator.of(context).pop(currentSelect);
    });
  }

  @override
  void searchRefreshData(searchData) async {
    keyword = searchData;
    page = 1;
    await post(refreshFuture, autoHandler: AutoHandler.Toast,
        onSuccess: (result) {
      data = getFromRequestResult(result, true);
      update();
    }, onFinally: () {
      if (data == null) {
        data = [];
      }
      update();
    });
    update();
  }

  @override
  FutureOr<List<PurchaseOrderEntity>> transformData(
      List<PurchaseOrderEntity> d, bool isCache) {
    return super.transformData(d, isCache);
  }

  @override
  List<PurchaseOrderEntity> get dataList => data;

  @override
  List<PurchaseOrderEntity> getFromRequestResult(
      Response result, bool isRefresh) {
    return getEntityFromResult(result);
  }

  @override
  Future get refreshFuture => dataFuture;
}
